package com.sy.wechat.service.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.sy.auth.service.SysUserService;
import com.sy.model.process.Process;
import com.sy.model.process.ProcessTemplate;
import com.sy.model.system.SysUser;
import com.sy.process.service.ProcessService;
import com.sy.process.service.ProcessTemplateService;
import com.sy.security.custom.LoginUserInfoHelper;
import com.sy.vo.process.ApprovalVo;
import com.sy.wechat.service.MessageService;
import lombok.SneakyThrows;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateData;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;

@Service
public class MessageServiceImp implements MessageService {

    @Autowired
    private ProcessService processService;
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private ProcessTemplateService processTemplateService;
    @Autowired
    private WxMpService wxMpService;

    // 推送给待审批的人员
    @SneakyThrows
    @Override
    public void pushPendingMessage(Long processId, Long userId, String taskId) {

        Process process = processService.getById(processId);
        SysUser sysUser = sysUserService.getById(userId);

        // 查询审批模板
        ProcessTemplate processTemplate = processTemplateService.getById(process.getProcessTemplateId());
        // 提交审批人
        SysUser submitSysUser = sysUserService.getById(process.getUserId());

        // 消息模板
        WxMpTemplateMessage wxMpTemplate = WxMpTemplateMessage.builder()
                .toUser(sysUser.getOpenId()) // 推送给谁(openId)
                .templateId("hHMluPg27ZyGaobvuabmrb7-ZOFOCXJElWvlH1LMHJY") // 消息模板id
                .url("http://8gqsyp.natappfree.cc/#/show/" + processId + "/" + taskId)// 跳转到详情
                .build();

        // 设置值
        JSONObject jsonObject = JSON.parseObject(process.getFormValues());
        JSONObject formShowData = jsonObject.getJSONObject("formShowData");
        StringBuffer content = new StringBuffer();
        for (Map.Entry entry : formShowData.entrySet()) {
            content.append(entry.getKey()).append("：").append(entry.getValue()).append("\n ");
        }
        wxMpTemplate.addData(new WxMpTemplateData("first", submitSysUser.getName()+"提交了"+processTemplate.getName()+"审批申请，请注意查看。", "#272727"));
        wxMpTemplate.addData(new WxMpTemplateData("keyword1", process.getProcessCode(), "#272727"));
        wxMpTemplate.addData(new WxMpTemplateData("keyword2", new DateTime(process.getCreateTime()).toString("yyyy-MM-dd HH:mm:ss"), "#272727"));
        wxMpTemplate.addData(new WxMpTemplateData("content", content.toString(), "#272727"));

        // 生成消息
        String msg = wxMpService.getTemplateMsgService().sendTemplateMsg(wxMpTemplate);
        System.out.println(msg);

    }

    @SneakyThrows
    @Override
    public void pushProcessedMessage(ApprovalVo approvalVo, Long userId) {

        Long processId = approvalVo.getProcessId();
        Integer status = approvalVo.getStatus();
        String taskId = approvalVo.getTaskId();

        Process process = processService.getById(processId);
        ProcessTemplate processTemplate = processTemplateService.getById(process.getProcessTemplateId());
        SysUser sysUser = sysUserService.getById(userId);
        SysUser currentSysUser = sysUserService.getById(LoginUserInfoHelper.getUserId());
        String openid = sysUser.getOpenId();

        WxMpTemplateMessage templateMessage = WxMpTemplateMessage.builder()
                .toUser(openid)//要推送的用户openid
                .templateId("HwC22Dt-dFoGVwKB7hS2kAzvptD_olxrirsJBA9ICtM")//模板id
                .url("http://8gqsyp.natappfree.cc/#/show/"+processId+ "/" + taskId)//点击模板消息要访问的网址
                .build();

        JSONObject jsonObject = JSON.parseObject(process.getFormValues());
        JSONObject formShowData = jsonObject.getJSONObject("formShowData");
        StringBuffer content = new StringBuffer();
        for (Map.Entry entry : formShowData.entrySet()) {
            content.append(entry.getKey()).append("：").append(entry.getValue()).append("\n ");
        }
        templateMessage.addData(new WxMpTemplateData("first", "你发起的"+processTemplate.getName()+"审批申请已经被处理了，请注意查看。", "#272727"));
        templateMessage.addData(new WxMpTemplateData("keyword1", process.getProcessCode(), "#272727"));
        templateMessage.addData(new WxMpTemplateData("keyword2", new DateTime(process.getCreateTime()).toString("yyyy-MM-dd HH:mm:ss"), "#272727"));
        templateMessage.addData(new WxMpTemplateData("keyword3", currentSysUser.getName(), "#272727"));
        templateMessage.addData(new WxMpTemplateData("keyword4", status == 1 ? "审批通过" : "审批拒绝", status == 1 ? "#009966" : "#FF0033"));
        templateMessage.addData(new WxMpTemplateData("content", content.toString(), "#272727"));

        String msg = wxMpService.getTemplateMsgService().sendTemplateMsg(templateMessage);
        System.out.println(msg);
    }
}
